package com.qf.chat.commons.utils;

import com.qf.chat.commons.exception.ServiceException;
import com.qf.chat.commons.r.Codes;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class UserUtils {

    /**
     * 解析jwt令牌，获取当前登录的用户id
     * @return
     */
    public static Integer getUid(){
        //获取当前用户的jwt令牌，并且解析出用户id
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Token");

        //解析令牌
        Integer uid = JwtUtils.parseJwtToken(token, "id");
        if (uid == null) {
            throw new ServiceException(Codes.TOKEN_ERROR);
        }
        return uid;
    }
}
